import subprocess
from PyQt5.QtCore import pyqtSignal, QObject
import os

class ServiceManager(QObject):
    """
    服务管理类，用于管理Windows服务或进程
    """
    service_restarted_signal = pyqtSignal(bool, str)
    
    def __init__(self):
        super().__init__()
        self.current_service_name = None
        self.current_service_path = None

    def set_current_service(self, service_name: str, service_path: str):
        """设置当前要操作的服务"""
        self.current_service_name = service_name
        self.current_service_path = service_path

    def start_service(self):
        """启动服务"""
        try:
            if not self.current_service_path:
                raise ValueError("服务路径未设置")

            # 检查文件是否存在
            if not os.path.exists(self.current_service_path):
                raise FileNotFoundError(f"服务程序不存在: {self.current_service_path}")

            # 启动服务
            subprocess.run([self.current_service_path], check=True)
            self.service_restarted_signal.emit(True, f"服务 {self.current_service_name} 启动成功")

        except Exception as e:
            error_msg = f"启动服务失败: {str(e)}"
            self.service_restarted_signal.emit(False, error_msg)
            raise Exception(error_msg)

    def stop_service(self):
        """停止服务"""
        try:
            if not self.current_service_name:
                raise ValueError("服务名称未设置")

            # 使用taskkill命令强制结束进程
            subprocess.run(['taskkill', '/F', '/IM', os.path.basename(self.current_service_path)], 
                         check=True, 
                         capture_output=True)
            self.service_restarted_signal.emit(True, f"服务 {self.current_service_name} 停止成功")

        except subprocess.CalledProcessError as e:
            if e.returncode == 128:  # 进程不存在的错误码
                # 如果进程不存在，我们认为这是正常的，因为服务可能本来就没在运行
                self.service_restarted_signal.emit(True, f"服务 {self.current_service_name} 已经停止")
            else:
                error_msg = f"停止服务失败: {e.stderr.decode('gbk')}"
                self.service_restarted_signal.emit(False, error_msg)
                raise Exception(error_msg)
        except Exception as e:
            error_msg = f"停止服务失败: {str(e)}"
            self.service_restarted_signal.emit(False, error_msg)
            raise Exception(error_msg)

    def restart_service(self, service_name: str, service_path: str):
        """重启服务"""
        try:
            self.set_current_service(service_name, service_path)
            self.stop_service()
            self.start_service()
        except Exception as e:
            error_msg = f"重启服务 {service_name} 失败: {str(e)}"
            self.service_restarted_signal.emit(False, error_msg)
            raise Exception(error_msg)

    def check_service_status(self):
        """检查服务状态"""
        try:
            if not self.current_service_path:
                return False

            # 使用tasklist命令检查进程是否存在
            result = subprocess.run(['tasklist', '/FI', f'IMAGENAME eq {os.path.basename(self.current_service_path)}'],
                                 capture_output=True,
                                 text=True)
            
            # 如果进程名在输出中，说明服务正在运行
            return os.path.basename(self.current_service_path).lower() in result.stdout.lower()

        except Exception:
            return False